//
//  EventDetail.swift
//  foodApp1
//
//  Created by Jenny Shi on 2018/2/18.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import UIKit
import os.log
import Hyphenate
import MobileCoreServices
import MBProgressHUD
import Alamofire

//代理返回数据用
protocol EventDetailDelegate {
    func didSaved(cuEvent0: CuEvent?,ownerGo0: String)
}

class EventDetail: UIViewController ,EMSelectItemViewControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
    
    @IBOutlet weak var src: UIScrollView!
    
    //邀请好友参加event返回的选择结果
    var selectedItems: Array<IEMUserModel>?
    //处理传回invite数据。只有1、3两种情况。此时eowner=loginOwner
    func didSelected(item: Array<IEMUserModel>?,groupId: String?) {
        //在这里合成guestStatus。以新选的为主。因为是自己创建的，所以可以在第一个上直接加eowner
        eguestStatus = eowner
        var guestNumber = 0
        if item != nil {
            selectedItems = Array(item!.reversed())
            for tmpItem in selectedItems! {
                if eowner.compare(tmpItem.hyphenateID).rawValue == 0 {
                    
                } else {
                    eguestStatus = eguestStatus + " " + tmpItem.hyphenateID
                    guestNumber = guestNumber + 1
                }
            }
        }
        inviteButton.setTitle("\(EnStatic.getWord(keyWord: "Invite"))(\(guestNumber))", for: .normal)
    }
    
    //定义闭包类型（参数和返回值类型）
    typealias getMyValueClosure = (_ myClass:CuEvent, _ myValueString:String)->Void
    // 声明一个闭包，类型是上面定义的类型，返回类型定义中的两个参数值
    var myClosure :getMyValueClosure?
    
    //声明，类型是上面定义的类型（代理中的方法名及参数类型），返回时执行代理中的方法，这里传进数据类型
    var delegate: EventDetailDelegate?
    
    //仅为保有navigation条，如果删掉就不能够直接增加左面的cancel按钮和右面的save按钮了
    //cancel和save按钮是程序中自定义的
    @IBOutlet weak var saveButtonDateSelector: UIBarButtonItem!

    //自定义图片：测试选图片用的，调通但未启用
    var myImageView: UIImageView = UIImageView(frame: CGRect(x: 20, y: 280, width: 160, height: 160))
    
    //event各个属性的值和临时属性
    var eid = "_id"
    var eowner = ""
    var edate = "date"
    var edateDate = Date() - 20 * 365 * 24 * 3600
    var eeventTitle = ""
    var edescription = ""
    var estartTime = "startTime"
    var eendTime = "endTime"
    var ecalendarType = "calendarType"
    var eeventType = "eventType"
    var etimeSensibility = "timeSensibility"
    var eguestStatus = ""
    
    //初始化invite按钮上面的数字和show invitation answer用
    var eguestDictionaryArray: [AnyObject] = [AnyObject]()
    
    //自定义控件变量：label、textField、textView、button
    var preTitleLabel = UILabel()
    var titleLabel = UILabel()
    var eeventTitleField = UITextView()
    var ownerLabel = UILabel()
    var eownerNameLabel = UILabel()
    var descriptionLabel = UILabel()
    var edescriptionView = UITextView()
    var dateLabel = UILabel()
    var dateButton = UIButton()
    var startTime = UILabel()
    var startTimeButton = UIButton()
    var endTime = UILabel()
    var endTimeButton = UIButton()
    var calendarType = UILabel()
    var calendarTypeButton = UIButton()
    var eventType = UILabel()
    var eventTypeButton = UIButton()
    var timeSensibility = UILabel()
    var timeSensibilityButton = UIButton()
    var inviteButton = UIButton()
    var showReplyButton = UIButton()
    var ifGoingLabel = UILabel()
    var ifGoingswitch = UISwitch()
    
    //中文选择时间用
    var hours = "10"
    var minutes = "30"
    var hoursButton = UIButton()

    //选择起始和终止时间用的临时UIKits变量
    var startEndTimeSelectView = UIView()
    var datePicker = UIDatePicker()
    var startDatePicker = UIDatePicker()
    var endDatePicker = UIDatePicker()
    var startEndTimeSelectButton = UIButton()
    
    //选择type的pickerView的临时UIKits变量
    var myTypeView = UIView()
    var myTypePickerView = UIPickerView()
    var myTypeButton = UIButton()

    //共用一个pickerView，用pickerViewForType区分
    var pickerViewForType: Int = EnStatic.calendarTypePicker
    var calendarTypeArray: [String] = [EnStatic.getOtherWord(keyWord: "public"),EnStatic.getOtherWord(keyWord: "private")]
    var eventTypeArray: [String] = [EnStatic.getWord(keyWord: "Work"),EnStatic.getWord(keyWord: "None-Work"),EnStatic.getWord(keyWord: "Out of Town")]
    var timeSensibilityArray: [String] = [EnStatic.getOtherWord(keyWord: "Free"),EnStatic.getOtherWord(keyWord: "Do not disturb"),EnStatic.getOtherWord(keyWord: "Text allowed"),EnStatic.getOtherWord(keyWord: "Call allowed")]
    var hourArray: [String] = ["0","1","2","3","4","5","6","7","8","9","10","11",
                               "12","13","14","15","16","17","18","19","20","21","22","23",]
    var minuteArray: [String] = ["0","1","2","3","4","5","6","7","8","9","10",
                                 "11","12","13","14","15","16","17","18","19","20",
                                 "21","22","23","24","25","26","27","28","29","30",
                                 "31","32","33","34","35","36","37","38","39","40",
                                 "41","42","43","44","45","46","47","48","49","50",
                                 "51","52","53","54","55","56","57","58","59",]

    //屏幕不含状态栏的大小
    var screenX : Int = 0
    var screenY : Int = 0
    var screenWidth : Int = 0
    var screenHeight : Int = 0
    
    var widthEverage : Int = 0
    var heightEverage : Int = 0
    
    //滚屏高度的扩展量
    var scrollSrcHeight : CGFloat = 100.0
    
    //传进来的参数
    var statusPara = StatusPara(hasFriend:false,friendOwner:"",loginOwner:"",sourceViewControllerType:1,dateTitle:"",date:Date(),calendarTypeNumber:0,matchOrFree:0,languageNow:"")
    //传进来的值
    var cuEvent : CuEvent?
    var dateTitle : String?
    var sourceViewControllerType : Int = EnStatic.fromCalendarWithoutSelectedDate
    var hasFriend:Bool = false
    var friendOwner : String?
    var matchOrFree = EnStatic.getMatchSlots
    var slot: Slot?
    
    //控制状态变量
    var saveButtonClickedTimes = 0
    var invitedFriendButtonClickedTimes = 0
    var invitedHowManyFriends = 0
    var alertCancel = 0
    var alertOk = 0
    var maxTime = Date()
    var minTime = Date()
    var ownerGo = "unread"

    //login的owner
    var loginOwner = ""
    
    @objc func keyboardWillShow(sender: NSNotification) {
        self.view.frame.origin.y = -150 // Move view 150 points upward
    }
    
    @objc func keyboardWillHide(sender: NSNotification) {
        self.view.frame.origin.y = 0 // Move view to original position
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        src.contentSize = CGSize(width: self.view.frame.width,height: self.view.frame.height + scrollSrcHeight)
        src.contentOffset = CGPoint(x: 0, y: 0)

//        NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        
//        NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

        // 设置传进来的参数
        if statusPara == statusPara {
            hasFriend = (statusPara?.hasFriend)!
            friendOwner = statusPara?.friendOwner
            loginOwner = (statusPara?.loginOwner)!
            dateTitle = statusPara?.dateTitle
            sourceViewControllerType = (statusPara?.sourceViewControllerType)!
            matchOrFree = (statusPara?.matchOrFree)!
        } else {
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd"
            dateTitle = dformatter.string(from: Date())
            loginOwner = EMClient.shared().currentUsername
        }
        
        //获取login的userID
        if loginOwner.isEmpty {
            loginOwner = EMClient.shared().currentUsername
        }
        
        //获取屏幕大小
        let screenApplicationBounds:CGRect = UIScreen.main.bounds
        let navigationHeight = UIApplication.shared.statusBarFrame.height
        
        screenX = Int(screenApplicationBounds.origin.x)
        screenY = Int(screenApplicationBounds.origin.y + navigationHeight)
        screenHeight = Int(screenApplicationBounds.height)
        screenWidth = Int(screenApplicationBounds.width)
        
        //自定义图片
        myImageView.image = UIImage(named: "defaultPhoto")
        let gesture = UITapGestureRecognizer(target: self, action: #selector(EventDetail.imageViewGestureTapped))
        myImageView.addGestureRecognizer(gesture)
        myImageView.isUserInteractionEnabled = true
        //暂时不启用。注意，也可能不是src而是view
        //        self.src.addSubview(myImageView)
        
        //自定义导航栏的标题和左右按钮
        let cancelButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Back"), style: .plain, target: self, action: #selector(EventDetail.cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = cancelButtonItem
        var saveButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Save"), style: .plain, target: self, action: #selector(EventDetail.saveButtonClicked))
        if sourceViewControllerType == EnStatic.fromEventListToSeeFriendsReply {
            if hasFriend {
                saveButtonItem = UIBarButtonItem(title: getNickNameWithUsername(username: friendOwner!), style: .plain, target: self, action: nil)
            } else {
                saveButtonItem = UIBarButtonItem(title: getNickNameWithUsername(username: loginOwner), style: .plain, target: self, action: nil)
            }
        }
        self.navigationItem.rightBarButtonItems?.removeAll()
        self.navigationItem.rightBarButtonItems?.append(saveButtonItem)
        self.navigationItem.title = " "

        //初始化修改时的变量值以及event起止时间等控制条件
        if let cuEvent = cuEvent {        //2查看回复或4回复
            //初始化变量。从传进来的cuEvent中取
            eid = cuEvent.eid
            eowner = cuEvent.eowner
            eeventTitle = cuEvent.eeventTitle
            edescription = cuEvent.edescription
            edate = cuEvent.edate
            estartTime = cuEvent.estartTime
            eendTime = cuEvent.eendTime
            ecalendarType = cuEvent.ecalendarType
            eeventType = cuEvent.eeventType
            etimeSensibility = cuEvent.etimeSensibility
            eguestStatus = cuEvent.eguestStatus
            //将eguestStatus解析到eguestDictionaryArray中，传到显示应答模块中
            let tmpDictionaryArray = eguestStatus.parseJSONString
            if tmpDictionaryArray != nil {
                eguestDictionaryArray = tmpDictionaryArray as! [AnyObject]
            }
            
            if cuEvent.eowner.compare(loginOwner).rawValue == 0 {
                //自己创建的，只能看别人的回复情况
            } else {    //别人邀请自己参加的
                ownerGo = cuEvent.eloginOwnerGo
            }
        } else {    //新增，1或3
            eid = ""
            edate = (statusPara?.dateTitle)!
            if EnStatic.languegeUsing().compare("en").rawValue == 0{
                estartTime = "11:00 AM"
                eendTime = "01:00 PM"
            } else {
                estartTime = "11:00"
                eendTime = "13:00"
            }
            //有slot传进来时
            if hasFriend {
                if slot != nil {
                    if !(slot?.estartTime.isEmpty)! && !(slot?.eendTime.isEmpty)! {
                        estartTime = (slot?.estartTime)!
                        eendTime = (slot?.eendTime)!
                    }
                }
            }
            ecalendarType = calendarTypeArray[0]
            eeventType = eventTypeArray[0]
            etimeSensibility = timeSensibilityArray[0]
            //创建时，缺省只有loginOwner一个人参加
            //login的owner的userid
            eowner = loginOwner
            eguestStatus = eowner
        }

        //event后端没有图片，所以暂时用前端的
        //            imageView1.image = CuEvent.ephoto

        //重新定义各个显示控件的尺寸、位置、颜色、形状等属性
        adapterUIAttribute()
        
        //设置textField和textView的代理
        eeventTitleField.delegate = self
//        eeventTitleField.returnKeyType = UIReturnKeyType.done
        edescriptionView.delegate = self
        
        //设置myTypePickerView的代理
        myTypePickerView.delegate = self
        myTypePickerView.dataSource = self
        
        //设置选择起止时间的窗口和标题
        setDateTimePicker()

        //设置选择calendarType等属性的pickerView
        setTypePicker()
        
        //在键盘上添加“完成“按钮，textView使用
        addDoneButtonOnKeyboard()
        
        //根据sourceViewControllerType调整活动控件
        setUIKitsEnableAndHidden()
        
        //match和free进来的不允许改日期，也不允许创建个人事件
        if hasFriend {
            dateButton.isEnabled = false
            calendarTypeButton.isEnabled = false
        }

        //设置save导航栏右上角save按钮状态（符合条件才能存盘返回上级窗口）
        updateSaveButtonState()
        
        print(eguestDictionaryArray)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //ok or cancel
    func myConfirm(title0: String, message0: String, cancel0:@escaping (Int?) -> Void, ok0: @escaping (Int?)-> Void) {
        self.alertOk = 0
        self.alertCancel = 0
        let alertController = UIAlertController(title: title0, message: message0, preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: EnStatic.getWord(keyWord: "Cancel"), style: .cancel, handler: {
            (action: UIAlertAction!) -> Void in
            self.alertCancel = 1
            cancel0(self.alertCancel)
        })
        alertController.addAction(cancelAction)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            (action: UIAlertAction!) -> Void in
            self.alertOk = 1
            ok0(self.alertOk)
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    //MARK: 导航栏左上角的cancel返回键和右上角的save返回键
    @objc func cancelButtonClicked() {

        switch sourceViewControllerType {
        case EnStatic.fromEventListToReplyFriend:        //答复去不去
            if ownerGo.compare("unread").rawValue == 0 {
                postEventStatus()
            } else {
                self.navigationController?.popViewController(animated: true)
            }
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:    //答复去不去，程序出口为主页面
            if ownerGo.compare("unread").rawValue == 0 {
                postEventStatus()
            } else {
                self.navigationController?.popViewController(animated: true)
                let mainVC = EMMainViewController()
                let nav = UINavigationController.init(rootViewController: mainVC)
                self.view.window?.rootViewController = nav
            }
        default:
            self.navigationController?.popViewController(animated: true)
        }

    }

    //提交对别人邀请事件的反馈意见，即情况4、5
    func postEventStatus() {

        var postGo = ownerGo
        if ownerGo.compare("unread").rawValue == 0 {
            postGo = "unread"
        }
        
        let cuHTTP = CUHTTP.instance()
        
        let urlstr = "eventStatus"
        
        var parameters: [String: Any]
        
            parameters = [
                "eventId" : eid,
                "status" : postGo,
                "guest" : loginOwner,
            ]
        
        print(parameters)
        
        cuHTTP.makePostData(url: urlstr, parameters: parameters,
                        success: {response in
                            print(response?.response?.statusCode ?? "??")      //成功时，返回200

                            //代理传值
                            if (self.delegate != nil) {
                                self.delegate?.didSaved(cuEvent0: self.cuEvent, ownerGo0: self.ownerGo)
                            }
                            //闭包传值
                            if (self.myClosure != nil){
                                self.myClosure!(self.cuEvent!, self.ownerGo)
                            }

                            //因notification进入的，返回到主菜单
                            if self.sourceViewControllerType == EnStatic.fromNotificationToReplyFriendThenToMainPage {
                                self.navigationController?.popViewController(animated: true)
                                let mainVC = EMMainViewController()
                                let nav = UINavigationController.init(rootViewController: mainVC)
                                self.view.window?.rootViewController = nav
                                return
                            }
                            
                            self.navigationController?.popViewController(animated: true)
                            
        } ,
                        failure: {response in
                            self.myAlert(message000: "save failed")
        }
        )
        
    }
    
    //创建，1和3的情况
    private func postOneEvent(event: CuEvent, createOrDelete: Int){

        //在此需要将event转换为JSONObject并写入parameters
        let value = event
        
        print(value)
        
        eowner = value.eowner
        eeventTitle = value.eeventTitle
        edescription = value.edescription
        edate = value.edate
        estartTime = value.estartTime
        eendTime = value.eendTime
        eguestStatus = value.eguestStatus
        ecalendarType = value.ecalendarType
        eeventType = value.eeventType
        etimeSensibility = value.etimeSensibility

        let cuHTTP = CUHTTP.instance()
        let urlstr = "event"
        var parameters: [String: Any]
        
        if createOrDelete == 0 {    //创建
            parameters = [
                "owner" : eowner,
                "calendarType" : ecalendarType,
                "eventType" : eeventType,
                "eventTitle" : eeventTitle,
                "description" : edescription,
                "date" : edate,
                "startTime" : estartTime,
                "endTime" : eendTime,
                "timeSensibility" : etimeSensibility,
                "guests" : eguestStatus,
            ]
        } else {    //删除
            parameters = [
                "eventId" : eid,
                "delete" : "true"
            ]
        }
        
        print(parameters)
        
        cuHTTP.makePostData(url: urlstr, parameters: parameters,
                        success: {response in
                            print(response?.response?.statusCode ?? "??")      //成功时，返回200

                            //代理传值
                            if (self.delegate != nil) {
                                self.delegate?.didSaved(cuEvent0: self.cuEvent, ownerGo0: self.ownerGo)
                            }
                            //闭包传值
                            if (self.myClosure != nil){
                                self.myClosure!(self.cuEvent!, self.ownerGo)
                            }
                            
                            self.navigationController?.popViewController(animated: true)
                            
        } ,
                        failure: {response in
                            self.myAlert(message000: "save failed")
        }
        )
        
    }
    
    //只有1、3、4、5四种情况，2不能存盘只能直接返回
    @objc private func saveButtonClicked() {

        //4、5，回复邀请
        if sourceViewControllerType == EnStatic.fromEventListToReplyFriend || sourceViewControllerType == EnStatic.fromNotificationToReplyFriendThenToMainPage {

            //写回going或not going
            postEventStatus()

            return

        }

        if ecalendarType.compare(EnStatic.getOtherWord(keyWord: "public")).rawValue == 0 {
            //1、3，创建public event
            if invitedFriendButtonClickedTimes <= 0 {
                myConfirm(title0: "", message0: EnStatic.getWord(keyWord: "Save and Exit without inviting anyone ?")
                    , cancel0: {alertCancel0 in
                        self.alertCancel = 1
                }
                    , ok0: {alertOk0 in
            
                        self.makePostEvent()
                        
                        self.postOneEvent(event: self.cuEvent!, createOrDelete: 0)
                        
                }
                )
                return
            }
        }
        
        //判断起始时间和终止时间的先后关系
        var oldStartTime = self.estartTime
        var oldEndTime = self.eendTime
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            //转换为24小时制
            oldStartTime = EventsViewController.hhmmaToHHmm(dateStr: oldStartTime)
            oldEndTime = EventsViewController.hhmmaToHHmm(dateStr: oldEndTime)
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        let tmpStartTime : Date = dateFormatter.date(from: "2000-01-01 " + oldStartTime)!
        let tmpEndTime : Date = dateFormatter.date(from: "2000-01-01 " + oldEndTime)!
        if tmpEndTime <= tmpStartTime {
            myAlert(message000: "start time can not be later than end time")
            return
        }
        //判断是否符合slot的限制
        if hasFriend {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            let endTime = slot?.eendTime
            let startTime = slot?.estartTime
            maxTime = formatter.date(from: "2000-01-01 " + endTime!)!
            minTime = formatter.date(from: "2000-01-01 " + startTime!)!
            startDatePicker.maximumDate = maxTime
            startDatePicker.minimumDate = minTime
            if tmpStartTime < minTime {
                myAlert(message000: "start time earlier than friend's free time")
                return
            }
            if tmpEndTime > maxTime {
                myAlert(message000: "end time later than friend's free time")
                return
            }
        }

        makePostEvent()

        self.postOneEvent(event: self.cuEvent!, createOrDelete: 0)
        
    }

    //将编辑结果合成CuEvent实例
    func makePostEvent() {
        let id = self.eid
        let owner = self.eowner
        let eventTitle = self.eeventTitleField.text ?? ""
        let description = self.edescriptionView.text ?? ""
        var calendarType = self.ecalendarType
        var eventType = self.eeventType
        var timeSensibility = self.etimeSensibility
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            calendarType = EnStatic.getOtherWord(keyWord: self.ecalendarType)
            eventType = self.eeventType
            timeSensibility = self.etimeSensibility
        } else {
            calendarType = EnStatic.chnToEnOtherWord(keyWord:self.ecalendarType)
            eventType = EnStatic.chnToEnWord(keyWord:self.eeventType)
            timeSensibility = EnStatic.chnToEnOtherWord(keyWord:self.etimeSensibility)
        }
        var guestStatus = self.eguestStatus
        let photo = self.myImageView.image
        let date = self.edate
        var startTime = self.estartTime
        var endTime = self.eendTime
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            startTime = EventsViewController.hhmmaToHHmm(dateStr: startTime)
        }
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            endTime = EventsViewController.hhmmaToHHmm(dateStr: endTime)
        }
        //个人事件删除已经邀请的好友
        if calendarType.compare("public").rawValue == 0 {
            
        } else {
            guestStatus = eowner
        }
        
        self.cuEvent = CuEvent(id: id, owner: owner, calendarType: calendarType, eventType: eventType, eventTitle: eventTitle, description: description, date: date, startTime: startTime, endTime: endTime, timeSensibility: timeSensibility, guestStatus: guestStatus, friendGo : "", photo: photo, loginOwnerGo : "")
    }
    
    // Disable the Save button if the necessary field is empty.
    private func updateSaveButtonState() {

        switch sourceViewControllerType {
        case EnStatic.fromEventListToSeeFriendsReply:        //2查看答复，没有save按钮
            return
        case EnStatic.fromEventListToReplyFriend:        //4答复去不去
            self.navigationItem.rightBarButtonItem?.isEnabled = true
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:        //5答复去不去，程序出口为主页面
            self.navigationItem.rightBarButtonItem?.isEnabled = true
        default:
            let etitle =  eeventTitleField.text ?? ""
            self.navigationItem.rightBarButtonItem?.isEnabled = !etitle.isEmpty && !edate.isEmpty && !estartTime.isEmpty && !eendTime.isEmpty && !etimeSensibility.isEmpty && !ecalendarType.isEmpty && !eeventType.isEmpty
        }

    }
    
    //MARK: 设置event起止时间
    func setDateTimePicker() {
        startEndTimeSelectView.isHidden = true
    }

    //选定起止时间的ok按钮
    @objc func okButtonTapped() {
        startEndTimeSelectView.isHidden = true
    }
    
    //日期选择器响应方法
    @objc func dateChanged(datePicker : UIDatePicker){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        //日期限制
        let minDay = Date()
        datePicker.minimumDate = minDay
        edate = formatter.string(from: datePicker.date)
        dateButton.setTitle(edate, for: UIControlState.normal)
    }
    
    @objc func startTimeChanged(startDatePicker : UIDatePicker){
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        if hasFriend {
            //时间限制
            let endTime = slot?.eendTime
            let startTime = slot?.estartTime
            maxTime = formatter.date(from: endTime!)!
            minTime = formatter.date(from: startTime!)!
            startDatePicker.maximumDate = maxTime
            startDatePicker.minimumDate = minTime
        }
        estartTime = formatter.string(from: startDatePicker.date)
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            estartTime = EventsViewController.HHmmTohhmma(dateStr: estartTime)
        }
        startTimeButton.setTitle(estartTime, for: UIControlState.normal)
    }
    
    @objc func endTimeChanged(endDatePicker : UIDatePicker){
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        if hasFriend {
            //时间限制
            let endTime = slot?.eendTime
            let startTime = slot?.estartTime
            maxTime = formatter.date(from: endTime!)!
            minTime = formatter.date(from: startTime!)!
            endDatePicker.maximumDate = maxTime
            endDatePicker.minimumDate = minTime
        }
        eendTime = formatter.string(from: endDatePicker.date)
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            eendTime = EventsViewController.HHmmTohhmma(dateStr: eendTime)
        }
        endTimeButton.setTitle(eendTime, for: UIControlState.normal)
    }
    
    //设置起止时间
    @objc func dateSet() {
        startEndTimeSelectView.isHidden = false
        datePicker.isHidden = false
        startDatePicker.isHidden = true
        endDatePicker.isHidden = true
    }
    @objc func startTimeSet() {
        startEndTimeSelectView.isHidden = false
        datePicker.isHidden = true
        startDatePicker.isHidden = false
        endDatePicker.isHidden = true
    }
    @objc func endTimeSet() {
        startEndTimeSelectView.isHidden = false
        datePicker.isHidden = true
        startDatePicker.isHidden = true
        endDatePicker.isHidden = false
    }

    //MARK: 设置calendarType等几个radio button值
    func setTypePicker(){
        myTypeView.isHidden = true
    }
    
    //设置选择框的列数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        var numberOfComponentsRet = 1
        if pickerViewForType == EnStatic.hourMinitePicker {
            numberOfComponentsRet = 2
        }
        return numberOfComponentsRet
    }
    
    //设置选择框的行数
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        if 0 == component {
            switch pickerViewForType {
            case EnStatic.calendarTypePicker:    //calendarType
                return calendarTypeArray.count
            case EnStatic.eventTypePicker:    //eventType
                return eventTypeArray.count
            case EnStatic.timesensibilityTypePicker:    //timeSensibility
                return timeSensibilityArray.count
            case EnStatic.hourMinitePicker:    //hour and minute
                return hourArray.count
            default:
                return 1
            }
        } else {
            return minuteArray.count
        }
    }
    
    //设置选择框各选项的内容
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        //赋值
        if 0 == component {
            switch pickerViewForType {
            case EnStatic.calendarTypePicker:    //calendarType
                return calendarTypeArray[row]
            case EnStatic.eventTypePicker:    //eventType
                return eventTypeArray[row]
            case EnStatic.timesensibilityTypePicker:    //timeSensibility
                return timeSensibilityArray[row]
            case EnStatic.hourMinitePicker:    //hour and minute
                return hourArray[row]
            default:
                return ""
            }
        }else {
            return minuteArray[row]
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //选中所执行的方法
        if 0 == component {
            switch pickerViewForType {
            case EnStatic.calendarTypePicker:    //calendarType
                ecalendarType = calendarTypeArray[row]
                calendarTypeButton.setTitle(ecalendarType, for: .normal)
                if row == 0 {
                    inviteButton.isEnabled = true
                    inviteButton.isHidden = false
                } else {
                    inviteButton.isEnabled = false
                    inviteButton.isHidden = true
                }
            case EnStatic.eventTypePicker:    //eventType
                eeventType = eventTypeArray[row]
                eventTypeButton.setTitle(eeventType, for: .normal)
            case EnStatic.timesensibilityTypePicker:    //timeSensibility
                etimeSensibility = timeSensibilityArray[row]
                timeSensibilityButton.setTitle(etimeSensibility, for: .normal)
            case EnStatic.hourMinitePicker:    //hour and minute
                hours = hourArray[row]
                hoursButton.setTitle(hours + ":" + minutes, for: .normal)
            default:
                ecalendarType = calendarTypeArray[row]
                calendarTypeButton.setTitle(ecalendarType, for: .normal)
            }
        }else {
            minutes = minuteArray[row]
            hoursButton.setTitle(hours + ":" + minutes, for: .normal)
        }
    }
    
    @objc func calendarTypeButtonClicked() {
        if ecalendarType.compare(EnStatic.getOtherWord(keyWord: "public")).rawValue == 0 {
            ecalendarType = EnStatic.getOtherWord(keyWord: "private")   //转换为personal
            inviteButton.isEnabled = false
            inviteButton.isHidden = true
        } else {
            ecalendarType = EnStatic.getOtherWord(keyWord: "public")
            inviteButton.isEnabled = true
            inviteButton.isHidden = false
        }
        calendarTypeButton.setTitle(ecalendarType, for: .normal)
    }
    
    @objc func eventTypeButtonClicked() {
        myTypeView.isHidden = false
        pickerViewForType = EnStatic.eventTypePicker
        myTypePickerView.reloadAllComponents()
        var valueMatchedPickerIndex = 0
        var loopPickerIndex = 0
        for loop0 in eventTypeArray {
            if eeventType.compare(loop0).rawValue == 0 {
                valueMatchedPickerIndex = loopPickerIndex
            }
            loopPickerIndex = loopPickerIndex + 1
        }
        myTypePickerView.selectRow(valueMatchedPickerIndex, inComponent: 0, animated: true)
    }
    
    @objc func timeSensibilityButtonClicked() {
        myTypeView.isHidden = false
        pickerViewForType = EnStatic.timesensibilityTypePicker
        myTypePickerView.reloadAllComponents()
        var valueMatchedPickerIndex = 0
        var loopPickerIndex = 0
        for loop0 in timeSensibilityArray {
            if etimeSensibility.compare(loop0).rawValue == 0 {
                valueMatchedPickerIndex = loopPickerIndex
            }
            loopPickerIndex = loopPickerIndex + 1
        }
        myTypePickerView.selectRow(valueMatchedPickerIndex, inComponent: 0, animated: true)
    }
    
    @objc func hourMinuteButtonClicked() {
        myTypeView.isHidden = false
        pickerViewForType = EnStatic.hourMinitePicker
        myTypePickerView.reloadAllComponents()
        var valueMatchedPickerIndex = 0
        var loopPickerIndex = 0
        for loop0 in hourArray {
            if hours.compare(loop0).rawValue == 0 {
                valueMatchedPickerIndex = loopPickerIndex
            }
            loopPickerIndex = loopPickerIndex + 1
        }
        myTypePickerView.selectRow(valueMatchedPickerIndex, inComponent: 0, animated: true)
        valueMatchedPickerIndex = 0
        loopPickerIndex = 0
        for loop0 in minuteArray {
            if minutes.compare(loop0).rawValue == 0 {
                valueMatchedPickerIndex = loopPickerIndex
            }
            loopPickerIndex = loopPickerIndex + 1
        }
        myTypePickerView.selectRow(valueMatchedPickerIndex, inComponent: 1, animated: true)
    }
    
    //myPicker的ok按钮
    @objc func okButtonMyPickerTapped() {
        myTypeView.isHidden = true
    }
    
    //MARK: 在键盘上添加“完成“按钮，用于textView
    func addDoneButtonOnKeyboard() {
        let doneToolbar = UIToolbar()
        //左侧的flexibleSpace
        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        //右侧的完成按钮
        let done: UIBarButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Done"), style: .done,target: self,action: #selector(doneButtonAction))
        var items:[UIBarButtonItem] = []
        items.append(flexSpace)
        items.append(done)
        doneToolbar.items = items
        doneToolbar.sizeToFit()
        self.eeventTitleField.inputAccessoryView = doneToolbar
        self.edescriptionView.inputAccessoryView = doneToolbar
    }
    
    //“完成“按钮点击响应，用于textView
    @objc func doneButtonAction() {
        //收起键盘
        self.eeventTitleField.resignFirstResponder()
        self.edescriptionView.resignFirstResponder()
    }
    
    //MARK: invite按钮的关联方法，构造选好友的类的实例。只有1、3两种情况。此时eowner=loginOwner
    @objc func inviteButtonClicked() {
        if ecalendarType.compare(EnStatic.getOtherWord(keyWord: "public")).rawValue == 0 {
            
        } else {
            //告警：个人事件不能邀请
            myAlert(message000: "personal event need not to invite")
            return
        }
        invitedFriendButtonClickedTimes = invitedFriendButtonClickedTimes + 1
        let selectItemVC = EMSelectItemViewController()
        let tmpArr = Array<IEMUserModel>()
        let tmpArray = Array((selectedItems ?? tmpArr).reversed())
        selectItemVC.selectedAry = tmpArray
        selectItemVC.selectType = EMSelectItemType.showSelected
        //传入聊天朋友id
        selectItemVC.statusPara = statusPara
        selectItemVC.delegate = self
        let nav = UINavigationController.init(rootViewController: selectItemVC)
        present(nav, animated: true, completion: nil)
    }
    
    //看自己创建的event中所邀请的好友的答复。情况2
    @objc func showGoingButtonClicked() {
        performSegue(withIdentifier: "eventToInvite", sender: self)
    }
    
    //MARK: UITextFieldDelegate

    internal func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        switch sourceViewControllerType {
        case EnStatic.fromEventListToSeeFriendsReply:       //只查看，删掉save按钮，只有show按钮有效
            //阻止键盘弹出
            return false
        case EnStatic.fromEventListToReplyFriend:           //答复去不去
            //阻止键盘弹出
            return false
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:    //答复去不去，程序出口为主页面
            return false
        default:
            return true
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Disable the Save button while editing.
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        updateSaveButtonState()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }

    //MARK: UITextViewDelegate
    
    // 文本框将要开始编辑
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        switch sourceViewControllerType {
        case EnStatic.fromEventListToSeeFriendsReply:       //只查看，删掉save按钮，只有show按钮有效
            //阻止键盘弹出
            return false
        case EnStatic.fromEventListToReplyFriend:           //答复去不去
            //阻止键盘弹出
            return false
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:    //答复去不去，程序出口为主页面
            return false
        default:
            return true
        }
    }

    // 文本框已经开始编辑
    func textViewDidBeginEditing(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = false
   }
    
    // 文本框将要结束编辑
    func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        return true
    }
    
    // 文本框已经结束编辑
    func textViewDidEndEditing(_ textView: UITextView) {
        updateSaveButtonState()
    }
    
    //  文本变更时被调用 现在是一个字符发生变化就会调用
    func textViewDidChange(_ textView: UITextView) {

    }
    
    // 光标移动时 选择范围发生变化
    func textViewDidChangeSelection(_ textView: UITextView) {

    }
    
    //MARK: UIImagePickerControllerDelegate
    
    @objc func imageViewGestureTapped() {
        
        // UIImagePickerController is a view controller that lets a user pick media from their photo library.
        let imagePickerController = UIImagePickerController()
        
        // Only allow photos to be picked, not taken.
        imagePickerController.sourceType = .photoLibrary
        
        // Make sure ViewController is notified when the user picks an image.
        imagePickerController.delegate = self
        
        present(imagePickerController, animated: true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        // Set photoImageView to display the selected image.
        myImageView.image = selectedImage

        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
        
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        super.prepare(for: segue, sender: sender)
        
        switch(segue.identifier ?? "") {
        //查看本人创建的event现在被邀请人的反馈意见，情况2
        case "eventToInvite":
            os_log("eventToInvite", log: OSLog.default, type: .debug)
            guard let inviteViewController = segue.destination as? InviteViewController else {
                fatalError("Unexpected destination: \(segue.destination)")
            }
            inviteViewController.guestDictionaryArray = eguestDictionaryArray
            inviteViewController.eventId = eid
            inviteViewController.sourceViewControllerType = sourceViewControllerType
        default:
            os_log("not invite segue", log: OSLog.default, type: .debug)
        }
        
    }
    
    //设置显示控件的Enable和Hidden
    func setUIKitsEnableAndHidden() {
        switch sourceViewControllerType {
        case EnStatic.fromCalendarWithoutSelectedDate:    //自由创建
            if ecalendarType.compare(EnStatic.getOtherWord(keyWord: "public")).rawValue == 0 {
                inviteButton.isHidden = false
            } else {
                inviteButton.isEnabled = false
                inviteButton.isHidden = true
            }
        case EnStatic.fromMatchFreeWithDateAndSlot:        //match和free的创建，只能是public
            if ecalendarType.compare(EnStatic.getOtherWord(keyWord: "public")).rawValue == 0 {
                inviteButton.isHidden = false
            } else {
                inviteButton.isEnabled = false
                inviteButton.isHidden = true
            }
        case EnStatic.fromEventListToSeeFriendsReply:       //只查看，删掉save按钮，只有show按钮有效
            eeventTitleField.isUserInteractionEnabled = true
            edescriptionView.isUserInteractionEnabled = true
            inviteButton.isEnabled = false
            inviteButton.isHidden = true
            showReplyButton.isEnabled = true
            dateButton.isEnabled = false
            startTimeButton.isEnabled = false
            endTimeButton.isEnabled = false
            calendarTypeButton.isEnabled = false
            eventTypeButton.isEnabled = false
            timeSensibilityButton.isEnabled = false
            grayFrameLine()
        case EnStatic.fromEventListToReplyFriend:           //答复去不去
            eeventTitleField.isUserInteractionEnabled = true
            edescriptionView.isUserInteractionEnabled = true
            inviteButton.isEnabled = false
            inviteButton.isHidden = true
            showReplyButton.isEnabled = true
            dateButton.isEnabled = false
            startTimeButton.isEnabled = false
            endTimeButton.isEnabled = false
            calendarTypeButton.isEnabled = false
            eventTypeButton.isEnabled = false
            timeSensibilityButton.isEnabled = false
            ifGoingswitch.isEnabled = true
            grayFrameLine()
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:    //答复去不去，程序出口为主页面
            eeventTitleField.isUserInteractionEnabled = true
            edescriptionView.isUserInteractionEnabled = true
            inviteButton.isEnabled = false
            inviteButton.isHidden = true
            showReplyButton.isEnabled = true
            dateButton.isEnabled = false
            startTimeButton.isEnabled = false
            endTimeButton.isEnabled = false
            calendarTypeButton.isEnabled = false
            eventTypeButton.isEnabled = false
            timeSensibilityButton.isEnabled = false
            ifGoingswitch.isEnabled = true
            grayFrameLine()
        default:
            _ = 0
        }
        
    }
    
    // MARK: - 重新定义各个显示控件的尺寸、位置、颜色、形状等属性
    func adapterUIAttribute() {
        
        let labelFromX = 20
        var labelFromY = 0
        var labelWidth = 0
        var fieldWidth = 0
        let labelHeight = 30
        
        var displayFromY = screenY + 16
        if sourceViewControllerType == EnStatic.fromCalendarWithoutSelectedDate || sourceViewControllerType == EnStatic.fromMatchFreeWithDateAndSlot {
            displayFromY = screenY - Int(scrollSrcHeight/2)   //src高度扩展量的一半
        }
        
        let navigationBarHeight = 40
        let toolBarHeight = 60
        
        //0:title,1:detail,2:owner,3:date,4:startTime,5:endTime,6:calendarType,7:eventType
        //8:timesensibility,9:inviteButton,10:replyButton,11:ifGoing
        var fieldIndex = ["1":[[1,0],[2,1],[3,3],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[9,9],[10,11]],"2":[[1,0],[2,1],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[10,10],[11,12]],"3":[[1,0],[2,1],[3,3],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[9,9],[10,11]],"4":[[1,0],[2,1],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[10,10],[11,12]],"5":[[1,0],[2,1],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[10,10],[11,12]]]
        
        var sourceViewControllerKey = "1"
        var totalLines = 13
        var totalFields = 11
        
        switch sourceViewControllerType {
        case EnStatic.fromCalendarWithoutSelectedDate:
            sourceViewControllerKey = "1"
            totalLines = 13
            totalFields = 11
        case EnStatic.fromEventListToSeeFriendsReply:
            sourceViewControllerKey = "2"
            totalLines = 13
            totalFields = 11
        case EnStatic.fromMatchFreeWithDateAndSlot:
            sourceViewControllerKey = "3"
            totalLines = 13
            totalFields = 11
        case EnStatic.fromEventListToReplyFriend:
            sourceViewControllerKey = "4"
            totalLines = 14
            totalFields = 12
        case EnStatic.fromNotificationToReplyFriendThenToMainPage:
            sourceViewControllerKey = "5"
            totalLines = 14
            totalFields = 12
        default:
            sourceViewControllerKey = "1"
            totalLines = 13
            totalFields = 11
        }

        //最小的iphone宽度也不会越界，即verticalAdd一定大于零
        let verticalAdd = (screenHeight - displayFromY - toolBarHeight - totalLines * labelHeight)/totalFields

        //字号
        let funtSize : CGFloat = 14.0
        
        //边框宽度和圆角半径
        let uiKitBorder : CGFloat = 1.0
        let uiKitCornerRadius : CGFloat = 4.0

        labelWidth = 105
        fieldWidth = screenWidth - (3 * labelFromX) - labelWidth

        //重新定义各个控件的位置和尺寸
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![0][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![0][1] * labelHeight
        preTitleLabel.frame = CGRect(x: labelFromX-8, y: labelFromY+((labelHeight-0)/2), width: 6, height: 6)
        preTitleLabel.text = "*"
        preTitleLabel.textColor = UIColor.red
        preTitleLabel.font=UIFont.systemFont(ofSize: funtSize)
        titleLabel.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        titleLabel.text = EnStatic.getWord(keyWord: "Title")
        titleLabel.textColor = UIColor.black
        titleLabel.font=UIFont.systemFont(ofSize: funtSize)
        eeventTitleField.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        eeventTitleField.text = eeventTitle
        eeventTitleField.backgroundColor = UIColor.clear
        eeventTitleField.font = UIFont.systemFont(ofSize: funtSize)
        eeventTitleField.layer.borderWidth = uiKitBorder
        eeventTitleField.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![1][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![1][1] * labelHeight
        descriptionLabel.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        descriptionLabel.text = EnStatic.getWord(keyWord: "Detail")
        descriptionLabel.textColor = UIColor.black
        descriptionLabel.font=UIFont.systemFont(ofSize: funtSize)
        edescriptionView.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: 2 * labelHeight)
        edescriptionView.text = edescription
        edescriptionView.font = UIFont.systemFont(ofSize: funtSize)
        edescriptionView.backgroundColor = UIColor.clear
        edescriptionView.layer.borderWidth = uiKitBorder
        edescriptionView.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![2][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![2][1] * labelHeight
        ownerLabel.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        ownerLabel.text = EnStatic.getWord(keyWord: "Owner")
        ownerLabel.textColor = UIColor.black
        ownerLabel.font=UIFont.systemFont(ofSize: funtSize)
        eownerNameLabel.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        //必须是eowner，不能用loginOwner，因为有他人邀请自己的情况，这时eowner为friend创建者，不是logonOwner
        eownerNameLabel.padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        eownerNameLabel.text = getNickNameWithUsername(username: eowner)
        eownerNameLabel.font = UIFont.systemFont(ofSize: funtSize)
        eownerNameLabel.layer.borderWidth = uiKitBorder
        eownerNameLabel.layer.borderColor = UIColor.lightGray.cgColor
        eownerNameLabel.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![3][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![3][1] * labelHeight
        dateLabel.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        dateLabel.text = EnStatic.getWord(keyWord: "Date")
        dateLabel.textColor = UIColor.black
        dateLabel.font=UIFont.systemFont(ofSize: funtSize)
        dateButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        dateButton.contentHorizontalAlignment = .left
        dateButton.titleEdgeInsets.left = 5
        dateButton.setTitle(edate, for: .normal)
        dateButton.addTarget(self, action: #selector(EventDetail.dateSet), for: UIControlEvents.touchUpInside)
        dateButton.setTitleColor(UIColor.black, for: .normal)
        dateButton.setTitleColor(UIColor.green, for: .highlighted)
        dateButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        dateButton.layer.borderWidth = uiKitBorder
        dateButton.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![4][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![4][1] * labelHeight
        startTime.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        startTime.text = EnStatic.getWord(keyWord: "Start Time")
        startTime.textColor = UIColor.black
        startTime.font=UIFont.systemFont(ofSize: funtSize)
        startTimeButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        startTimeButton.contentHorizontalAlignment = .left
        startTimeButton.titleEdgeInsets.left = 5
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            //转换为12小时制
            startTimeButton.setTitle(EventsViewController.HHmmTohhmma(dateStr: estartTime), for: .normal)
        } else {
            //直接用24小时制
            startTimeButton.setTitle(estartTime, for: .normal)
        }
        startTimeButton.addTarget(self, action: #selector(EventDetail.startTimeSet), for: UIControlEvents.touchUpInside)
        startTimeButton.setTitleColor(UIColor.black, for: .normal)
        startTimeButton.setTitleColor(UIColor.green, for: .highlighted)
        startTimeButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        startTimeButton.layer.borderWidth = uiKitBorder
        startTimeButton.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![5][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![5][1] * labelHeight
        endTime.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        endTime.text = EnStatic.getWord(keyWord: "End Time")
        endTime.textColor = UIColor.black
        endTime.font=UIFont.systemFont(ofSize: funtSize)
        endTimeButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        endTimeButton.contentHorizontalAlignment = .left
        endTimeButton.titleEdgeInsets.left = 5
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            //转换为12小时制
            endTimeButton.setTitle(EventsViewController.HHmmTohhmma(dateStr: eendTime), for: .normal)
        } else {
            //直接用24小时制
            endTimeButton.setTitle(eendTime, for: .normal)
        }
        endTimeButton.addTarget(self, action: #selector(EventDetail.endTimeSet), for: UIControlEvents.touchUpInside)
        endTimeButton.setTitleColor(UIColor.black, for: .normal)
        endTimeButton.setTitleColor(UIColor.green, for: .highlighted)
        endTimeButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        endTimeButton.layer.borderWidth = uiKitBorder
        endTimeButton.layer.cornerRadius = uiKitCornerRadius
        
        //not used this button
/*
        labelFromY = displayFromY + navigationBarHeight + 6 * verticalAdd + 6 * labelHeight
        hoursButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        hoursButton.contentHorizontalAlignment = .left
        hoursButton.titleEdgeInsets.left = 5
        hoursButton.setTitle(hours + ":" + minutes, for: .normal)
        hoursButton.addTarget(self, action: #selector(EventDetail.hourMinuteButtonClicked), for: UIControlEvents.touchUpInside)
        hoursButton.setTitleColor(UIColor.black, for: .normal)
        hoursButton.setTitleColor(UIColor.green, for: .highlighted)
        hoursButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        hoursButton.layer.borderWidth = uiKitBorder
        hoursButton.layer.cornerRadius = uiKitCornerRadius
 */
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![6][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![6][1] * labelHeight
        calendarType.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        calendarType.text = EnStatic.getWord(keyWord: "Calendar Type")
        calendarType.textColor = UIColor.black
        calendarType.font=UIFont.systemFont(ofSize: funtSize)
        calendarTypeButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        calendarTypeButton.contentHorizontalAlignment = .left
        calendarTypeButton.titleEdgeInsets.left = 5
        calendarTypeButton.setTitle(ecalendarType, for: .normal)
        calendarTypeButton.addTarget(self, action: #selector(EventDetail.calendarTypeButtonClicked), for: UIControlEvents.touchUpInside)
        calendarTypeButton.setTitleColor(UIColor.black, for: .normal)
        calendarTypeButton.setTitleColor(UIColor.green, for: .highlighted)
        calendarTypeButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        calendarTypeButton.layer.borderWidth = uiKitBorder
        calendarTypeButton.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![7][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![7][1] * labelHeight
        eventType.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        eventType.text = EnStatic.getWord(keyWord: "Event Type")
        eventType.textColor = UIColor.black
        eventType.font=UIFont.systemFont(ofSize: funtSize)
        eventTypeButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        eventTypeButton.contentHorizontalAlignment = .left
        eventTypeButton.titleEdgeInsets.left = 5
        eventTypeButton.setTitle(eeventType, for: .normal)
        eventTypeButton.addTarget(self, action: #selector(EventDetail.eventTypeButtonClicked), for: UIControlEvents.touchUpInside)
        eventTypeButton.setTitleColor(UIColor.black, for: .normal)
        eventTypeButton.setTitleColor(UIColor.green, for: .highlighted)
        eventTypeButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        eventTypeButton.layer.borderWidth = uiKitBorder
        eventTypeButton.layer.cornerRadius = uiKitCornerRadius
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![8][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![8][1] * labelHeight
        timeSensibility.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        timeSensibility.text = "Time Sensibility".localized()
        timeSensibility.textColor = UIColor.black
        timeSensibility.font=UIFont.systemFont(ofSize: funtSize)
        timeSensibilityButton.frame = CGRect(x: (labelFromX + labelWidth + 10), y: labelFromY, width: fieldWidth, height: labelHeight)
        timeSensibilityButton.contentHorizontalAlignment = .left
        timeSensibilityButton.titleEdgeInsets.left = 5
        timeSensibilityButton.setTitle(etimeSensibility, for: .normal)
        timeSensibilityButton.addTarget(self, action: #selector(EventDetail.timeSensibilityButtonClicked), for: UIControlEvents.touchUpInside)
        timeSensibilityButton.setTitleColor(UIColor.black, for: .normal)
        timeSensibilityButton.setTitleColor(UIColor.green, for: .highlighted)
        timeSensibilityButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        timeSensibilityButton.layer.borderWidth = uiKitBorder
        timeSensibilityButton.layer.cornerRadius = uiKitCornerRadius
        
        let actionWidth = labelWidth + 10 + fieldWidth
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![9][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![9][1] * labelHeight
        inviteButton.frame = CGRect(x: labelFromX, y: labelFromY, width: actionWidth, height: labelHeight * 2)
        invitedHowManyFriends = eguestDictionaryArray.count
        for thisGuest in eguestDictionaryArray {
            if thisGuest["guest"] == nil {
                //异常，不处理
            } else {
                if eowner.compare(thisGuest["guest"] as! String).rawValue == 0 {
                    invitedHowManyFriends = invitedHowManyFriends - 1
                }
            }
        }
        inviteButton.setTitle("\(EnStatic.getWord(keyWord: "Invite"))(\(invitedHowManyFriends))", for: .normal)
        inviteButton.addTarget(self, action: #selector(EventDetail.inviteButtonClicked), for: UIControlEvents.touchUpInside)
        inviteButton.setTitleColor(UIColor.white, for: .normal)
        inviteButton.setTitleColor(UIColor.green, for: .highlighted)
        inviteButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        inviteButton.backgroundColor = UIColor.blue
        inviteButton.layer.borderWidth = uiKitBorder
        inviteButton.layer.cornerRadius = uiKitCornerRadius * 3
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![10][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![10][1] * labelHeight
        showReplyButton.frame = CGRect(x: labelFromX, y: labelFromY, width: actionWidth, height: labelHeight * 2)
        showReplyButton.setTitle(EnStatic.getWord(keyWord: "Show responses"), for: .normal)
        showReplyButton.addTarget(self, action: #selector(EventDetail.showGoingButtonClicked), for: UIControlEvents.touchUpInside)
        showReplyButton.setTitleColor(UIColor.white, for: .normal)
        showReplyButton.setTitleColor(UIColor.green, for: .highlighted)
        showReplyButton.titleLabel?.font = UIFont.systemFont(ofSize: funtSize)
        showReplyButton.backgroundColor = UIColor.blue
        showReplyButton.layer.borderWidth = uiKitBorder
        showReplyButton.layer.cornerRadius = uiKitCornerRadius * 3
        
        labelFromY = displayFromY + navigationBarHeight + fieldIndex[sourceViewControllerKey]![11][0] * verticalAdd + fieldIndex[sourceViewControllerKey]![11][1] * labelHeight
        ifGoingLabel.frame = CGRect(x: labelFromX, y: labelFromY, width: labelWidth, height: labelHeight)
        ifGoingLabel.text = EnStatic.getWord(keyWord: ownerGo)
        ifGoingLabel.textColor = UIColor.black
        ifGoingLabel.font=UIFont.systemFont(ofSize: funtSize)
        ifGoingswitch.frame = CGRect(x: 0, y: 0, width: 60, height: 40)
        ifGoingswitch.tintColor = UIColor.lightGray
        //设置位置（开关大小无法设置）
        ifGoingswitch.center = CGPoint(x:screenWidth/2, y:labelFromY + labelHeight/2)
        ifGoingswitch.addTarget(self, action: #selector(switchDidChange), for:.valueChanged)
        
        //设置reply时的初始颜色。只有情况4和5即回复别人邀请时才需要变色，其他情况1、3为创建，2为查看，都不需要变色
        if sourceViewControllerType == EnStatic.fromEventListToReplyFriend || sourceViewControllerType == EnStatic.fromNotificationToReplyFriendThenToMainPage {  //别人邀请我的，我回复去不去
            switch ownerGo {
            case "going":
                self.view.backgroundColor = BrightBlueColor
                ifGoingswitch.setOn(true, animated: true)
            case "not going":
                self.view.backgroundColor = OrangeRedColor
                ifGoingswitch.setOn(false, animated: true)
            case "unread":
                self.view.backgroundColor = WhiteColor
                ifGoingswitch.setOn(false, animated: true)
            default:
                self.view.backgroundColor = TextViewBorderColor
                ifGoingswitch.setOn(false, animated: true)
            }
        }
        
        //选择起始和终止时间用的临时UIKits变量
        startEndTimeSelectView.frame = CGRect(x: 30, y: 100, width: screenWidth - 60, height: 300)
        datePicker.frame = CGRect(x:20, y:0, width:screenWidth - 100, height:240)
        //注意：NSString.length和String.characters.count只有在半角字符时才相同
        //全角字符NSString.length算两个而String.characters.count算一个。此处全是半角字符所以才能用
        var nsValue = self.edate as NSString
        if nsValue.length == 10 {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            self.edateDate = formatter.date(from: self.edate)!
            self.datePicker.setDate(self.edateDate, animated: true)
        }
        var tmpTime = " "
        startDatePicker.frame = CGRect(x:20, y:0, width:screenWidth - 100, height:240)
        nsValue = self.estartTime as NSString
        if nsValue.length >= 5 {
            if EnStatic.languegeUsing().compare("en").rawValue == 0{
                tmpTime = EventsViewController.hhmmaToHHmm(dateStr: estartTime)
            } else {
                tmpTime = estartTime
            }
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            self.edateDate = formatter.date(from: "2000-01-01 " + tmpTime)!
            self.startDatePicker.setDate(self.edateDate, animated: true)
        }
        endDatePicker.frame = CGRect(x:20, y:0, width:screenWidth - 100, height:240)
        nsValue = self.eendTime as NSString
        if nsValue.length >= 5 {
            if EnStatic.languegeUsing().compare("en").rawValue == 0{
                tmpTime = EventsViewController.hhmmaToHHmm(dateStr: eendTime)
            } else {
                tmpTime = eendTime
            }
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            self.edateDate = formatter.date(from: "2000-01-01 " + tmpTime)!
            self.endDatePicker.setDate(self.edateDate, animated: true)
        }
        startEndTimeSelectButton.frame = CGRect(x: screenWidth/2 - 60, y: 240, width: 60, height: 30)
        startEndTimeSelectView.layer.borderWidth=1
        startEndTimeSelectView.layer.cornerRadius=10
        startEndTimeSelectView.backgroundColor = UIColor.lightGray
        
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            datePicker.locale = NSLocale(localeIdentifier: "en_US") as Locale
            datePicker.datePickerMode = UIDatePickerMode.date
        } else {
            datePicker.locale = Locale(identifier: "zh_CN")
            datePicker.datePickerMode = UIDatePickerMode.date
        }
        datePicker.setValue(UIColor.black, forKey: "textColor")
        datePicker.addTarget(self, action: #selector(dateChanged),
                             for: .valueChanged)
        
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            startDatePicker.locale = Locale(identifier: "en_US")
            startDatePicker.datePickerMode = UIDatePickerMode.time
        } else {
            startDatePicker.locale = Locale(identifier: "zh_CN")
//            startDatePicker.datePickerMode = UIDatePickerMode.countDownTimer
            startDatePicker.datePickerMode = UIDatePickerMode.time
        }
        startDatePicker.setValue(UIColor.black, forKey: "textColor")
        startDatePicker.addTarget(self, action: #selector(startTimeChanged),
                                  for: .valueChanged)
        
        if EnStatic.languegeUsing().compare("en").rawValue == 0 {
            endDatePicker.locale = Locale(identifier: "en_US")
            endDatePicker.datePickerMode = UIDatePickerMode.time
        } else {
            endDatePicker.locale = Locale(identifier: "zh_CN")
//            endDatePicker.datePickerMode = UIDatePickerMode.countDownTimer
            endDatePicker.datePickerMode = UIDatePickerMode.time
        }
        endDatePicker.addTarget(self, action: #selector(endTimeChanged),
                                for: .valueChanged)
        
        startEndTimeSelectButton.setTitle(EnStatic.getWord(keyWord: "OK"), for: UIControlState.normal)
        startEndTimeSelectButton.addTarget(self, action: #selector(okButtonTapped), for: .touchUpInside)

        startEndTimeSelectView.addSubview(datePicker)
        startEndTimeSelectView.addSubview(startDatePicker)
        startEndTimeSelectView.addSubview(endDatePicker)
        startEndTimeSelectView.addSubview(startEndTimeSelectButton)
        
        //选择type的pickerView的临时UIKits变量
        myTypeView.frame = CGRect(x: 30, y: 160, width: screenWidth - 60, height: 200)
        myTypePickerView.frame = CGRect(x: 40, y: 0, width: screenWidth - 160, height: 160)
        myTypeButton.frame = CGRect(x: screenWidth/2 - 60, y: 160, width: 60, height: 30)
        myTypeView.layer.borderWidth=1
        myTypeView.layer.cornerRadius=10
        myTypeView.backgroundColor = UIColor.lightGray
        myTypeButton.setTitle(EnStatic.getWord(keyWord: "OK"), for: UIControlState.normal)
        myTypeButton.addTarget(self, action: #selector(okButtonMyPickerTapped), for: .touchUpInside)
        //设置选择框的默认值：第一行第一列
        myTypePickerView.selectRow(0,inComponent:0,animated:true)
        //        myTypePickerView.selectRow(2,inComponent:1,animated:true)
        //        myTypePickerView.selectRow(3,inComponent:2,animated:true)
        myTypeView.addSubview(myTypePickerView)
        myTypeView.addSubview(myTypeButton)

        //关联控件以显示
        //设置窗口滚动。只有情况1和3即创建event时才需要滚动
        if sourceViewControllerType == EnStatic.fromCalendarWithoutSelectedDate || sourceViewControllerType == EnStatic.fromMatchFreeWithDateAndSlot {
            self.src.addSubview(preTitleLabel)
            self.src.addSubview(titleLabel)
            self.src.addSubview(eeventTitleField)
            //        self.src.addSubview(ownerLabel)
            //        self.src.addSubview(eownerNameLabel)
            self.src.addSubview(descriptionLabel)
            self.src.addSubview(edescriptionView)
            self.src.addSubview(inviteButton)
            self.src.addSubview(startTime)
            self.src.addSubview(startTimeButton)
            self.src.addSubview(endTime)
            self.src.addSubview(endTimeButton)
            self.src.addSubview(calendarType)
            self.src.addSubview(calendarTypeButton)
            self.src.addSubview(eventType)
            self.src.addSubview(eventTypeButton)
            self.src.addSubview(timeSensibility)
            self.src.addSubview(timeSensibilityButton)
            self.src.addSubview(dateLabel)
            self.src.addSubview(dateButton)
            self.src.addSubview(startEndTimeSelectView)
            self.src.addSubview(myTypeView)
            
            //不用自定义时间选择器
            //       self.src.addSubview(hoursButton)
            
        } else {
            self.view.addSubview(preTitleLabel)
            self.view.addSubview(titleLabel)
            self.view.addSubview(eeventTitleField)
            self.view.addSubview(ownerLabel)
            self.view.addSubview(eownerNameLabel)
            self.view.addSubview(descriptionLabel)
            self.view.addSubview(edescriptionView)
            //2的public有show按钮，4和5有show按钮和going的switch
            switch sourceViewControllerType {
            case EnStatic.fromEventListToSeeFriendsReply:
                if ecalendarType.compare(EnStatic.getWord(keyWord: "public")).rawValue == 0 {
                    self.view.addSubview(showReplyButton)
                }
            case EnStatic.fromEventListToReplyFriend:
                self.view.addSubview(showReplyButton)
                self.view.addSubview(ifGoingLabel)
                self.view.addSubview(ifGoingswitch)
            case EnStatic.fromNotificationToReplyFriendThenToMainPage:
                self.view.addSubview(showReplyButton)
                self.view.addSubview(ifGoingLabel)
                self.view.addSubview(ifGoingswitch)
            default:
                _ = 0
            }
            self.view.addSubview(startTime)
            self.view.addSubview(startTimeButton)
            self.view.addSubview(endTime)
            self.view.addSubview(endTimeButton)
            self.view.addSubview(calendarType)
            self.view.addSubview(calendarTypeButton)
            self.view.addSubview(eventType)
            self.view.addSubview(eventTypeButton)
            self.view.addSubview(timeSensibility)
            self.view.addSubview(timeSensibilityButton)
            self.view.addSubview(dateLabel)
            self.view.addSubview(dateButton)
            self.view.addSubview(startEndTimeSelectView)
            self.view.addSubview(myTypeView)
            
            //不用自定义时间选择器
            //       self.view.addSubview(hoursButton)
            
        }

    }

    //不可编辑时控件边框为暗线
    func grayFrameLine() {
        eeventTitleField.layer.borderColor = UIColor.lightGray.cgColor
        eeventTitleField.layer.borderColor = UIColor.lightGray.cgColor
        edescriptionView.layer.borderColor = UIColor.lightGray.cgColor
        dateButton.layer.borderColor = UIColor.lightGray.cgColor
        startTimeButton.layer.borderColor = UIColor.lightGray.cgColor
        endTimeButton.layer.borderColor = UIColor.lightGray.cgColor
        calendarTypeButton.layer.borderColor = UIColor.lightGray.cgColor
        eventTypeButton.layer.borderColor = UIColor.lightGray.cgColor
        timeSensibilityButton.layer.borderColor = UIColor.lightGray.cgColor
    }

    @objc func switchDidChange(){
        if ifGoingswitch.isOn {
            ownerGo = "going"
            self.view.backgroundColor = BrightBlueColor
        } else {
            ownerGo = "not going"
            self.view.backgroundColor = OrangeRedColor
        }
        ifGoingLabel.text = EnStatic.getWord(keyWord: ownerGo)
    }

    //简化版 Int(str)
    open class func StringToInt(str:String)->(Int){
        
        let string = str
        var cgInt: Int = 0
        
        if let doubleValue = Double(string)
        {
            cgInt = Int(doubleValue)
        }
        return cgInt
        
    }
    
    func getNickNameWithUsername(username : String) -> String {
        let entity = EMUserProfileManager.sharedInstance.getUserProfileByUsername(username: username)
        if entity?.nickname != nil && (entity?.nickname?.count)! > 0 {
            return (entity?.nickname)!
        }
        return username
    }
    
}

extension UITextField {
    func setLeftPaddingPoints(_ amount:CGFloat){
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
        self.leftView = paddingView
        self.leftViewMode = .always
    }
    func setRightPaddingPoints(_ amount:CGFloat) {
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
        self.rightView = paddingView
        self.rightViewMode = .always
    }
}

extension UILabel {
    private struct AssociatedKeys {
        static var padding = UIEdgeInsets()
    }
    
    public var padding: UIEdgeInsets? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    
    override open func draw(_ rect: CGRect) {
        if let insets = padding {
            self.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
        } else {
            self.drawText(in: rect)
        }
    }
    
    override open var intrinsicContentSize: CGSize {
        guard let text = self.text else { return super.intrinsicContentSize }
        
        var contentSize = super.intrinsicContentSize
        var textWidth: CGFloat = frame.size.width
        var insetsHeight: CGFloat = 0.0
        
        if let insets = padding {
            textWidth -= insets.left + insets.right
            insetsHeight += insets.top + insets.bottom
        }
        
        let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
                                        options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                        attributes: [NSAttributedStringKey.font: self.font], context: nil)
        
        contentSize.height = ceil(newSize.size.height) + insetsHeight
        
        return contentSize
    }
}
